<?php

namespace backend\models;

/**
 * @author  shuang
 * @date    2016-10-22 16:35:01
 * @version V1.0
 * @desc    
 */
use common\models\TaskPrice;
use yii\behaviors\TimestampBehavior;
use common\components\MTools;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use Yii;

class MY_TaskPrice extends TaskPrice {
    /*
     * 设置表操作行为动作
     * return array
     */

    public function behaviors() {
        return[
            [
                'class' => TimestampBehavior::className()
            ]
        ];
    }

    /*
     * 配置列表查询数据
     * 条件
     * return object
     */

    public static function getList() {
        $query = MY_TaskPrice::find()->with(["typeID", "gradeID"]);
        $sort = Yii::$app->request->get("sort");
        $order = Yii::$app->request->get("order");
        $query->orderBy($sort . " " . $order);
        $countQuery = clone $query;
        $offset = Yii::$app->request->get("offset");
        $limit = Yii::$app->request->get("limit");
        $totalCount = $countQuery->count();
        $res = $query->offset($offset)->limit($limit)->asArray()->all();
        return ["total" => $totalCount, "data" => $res];
    }

    /*
     * 关联字典表  任务类型
     */

    public function getTypeID() {

        return $this->hasOne(MY_Dictionary::className(), ['id' => 'typeid']);
    }

    /*
     * 关联代理级别  
     */

    public function getGradeID() {

        return $this->hasOne(MY_Grade::className(), ['id' => 'gradeid']);
    }

    /*
     * 插入、更新数据
     * @params $data array
     * @params $id int 主键
     * return boolean 
     */

    public static function createData($id = null) {
        $model = $id ? MY_TaskPrice::findOne($id) : new MY_TaskPrice();
        try {
            $model->load(Yii::$app->request->post());
            return MTools::saveModel($model);
        } catch (Exception $e) {
            throw $e;
        }
    }

    /*
     * 获取任务类型相关属性
     * return array
     */

    public static function getTaskAttributes() {
        $res = MY_TaskPrice::find()
                ->with(["typeID"])
                ->orderBy("price asc")->asArray()->all();
        $temp = [];
        foreach ($res as $item) {
            $temp[$item["typeid"]."-".$item["gradeid"]]["priceData"][] = ["id"=>$item["id"],"value" => $item["price"]];
            if ($temp[$item["typeid"]."-".$item["gradeid"]]) {
                if (ArrayHelper::getValue($item, "typeID.description")) {
                    $attributes = Json::decode(ArrayHelper::getValue($item, "typeID.description"));
                    foreach ($attributes as $attribute => $value) {
                        if (!$value) {
                            $temp[$item["typeid"]."-".$item["gradeid"]][$attribute] = true;
                        } else {
                            $temp[$item["typeid"]."-".$item["gradeid"]][$attribute] = $value;
                        }
                    }
                }
            }
        }
        return $temp;
    }

}
